package com.by.common.controller;

import com.by.common.entity.ResultBean;
import com.by.common.ex.ValidateException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class BaseController {
    private final int SUCCESS=200;

    private final int FAIL=0;

    /*
    * 操作成功 msg:消息描述
    * */
    protected ResultBean success(String msg){
        return convert(SUCCESS,msg,null);
    }
    /*
    * 相应失败 msg:消息描述 data:接口数据
    * */
    protected ResultBean success(String msg,Object data){
        return convert(SUCCESS,msg,data);
    }
    /*
    * 操作失败
    * */
    protected ResultBean fail(String msg){
        return convert(FAIL,msg,null);
    }
    /*
     * 操作失败
     * */
    protected ResultBean fail(String msg,Object data){
        return convert(FAIL,msg,data);
    }

    /*
    * 保存结果
    * */
    protected ResultBean saveResult(int rs){
        return rs==1?success("保存成功"):fail("保存失败");
    }

    /*
    * 修改结果
    * */
    protected ResultBean updateResult(int rs){
        return rs==1?success("修改成功"):fail("修改失败");
    }
    /*
    *
    * 删除结果
    * */
    protected ResultBean deleteResult(int rs){
        return rs==1?success("删除成功"):fail("删除失败");
    }
    /*
    * 转换成统一结果
    *
    * */
   ResultBean convert(int code,String msg,Object data){
        return new ResultBean(code,msg,data);
   }




//封装的验证信息
   protected  void validate(BindingResult result){
       //获取验证信息
       List<FieldError> errors = result.getFieldErrors();
       if (errors.size() > 0) {
           Map<String,String> map = new HashMap<>();
           errors.forEach(el -> {
               map.put(el.getField(), el.getDefaultMessage());
           });
//           抛出自定义验证异常
           throw new ValidateException(map);
       }
   }

}
